package com.ghh.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.ghh.constant.MessageConstant;
import com.ghh.constant.RedisMessageConstant;
import com.ghh.entity.Result;
import com.ghh.pojo.Order;
import com.ghh.service.OrderService;
import com.ghh.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        String telePhone = (String) map.get("telephone");
        //从Resid中获取保存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telePhone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        //将用户输入的验证码与Redis中的进行比对
        if (validateCodeInRedis!=null&&validateCode!=null&&validateCode.equals(validateCodeInRedis)){
            //比对成功，进行预约业务处理
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = null ;
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }
            //预约成功，给用户发送短信
            if (result.isFlag()){
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telePhone,(String)map.get("orderData"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }else {
            //比对失败，返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) throws Exception {
        try {
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }
}
